<template>
  <div class="app-main-container" style="padding-top: 20px;">
    <el-tabs v-model="tabIndex" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="(item, index) in tabList"
        :key="index"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>
    <div v-show="tabIndex === 'first'">
      <div class="doumee-filter">
        <el-form inline @submit.native.prevent>
          <el-form-item label="设备状态:">
            <el-select v-model="filters.state" placeholder="请选择设备状态" clearable>
              <el-option
                v-for="item in stateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备在线状态:">
            <el-select v-model="filters.connectStatus" placeholder="请选择设备在线状态" clearable>
              <el-option
                v-for="item in connectStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-preventReClick type="primary" @click="getList(1)">查找</el-button>
            <el-button v-preventReClick @click="clear">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="active" @tab-click="handleClick">
        <el-tab-pane
          v-for="(model, index) in manufacturerList"
          :key="index"
          :label="model.manufacturer"
          :name="index.toString()"
        >
          <div class="doumee-filter manufacturer">
            <div>
              <el-button v-if="meta.indexOf('deviceTicketAdd') > -1" v-preventReClick type="primary" @click="addDevice">新增</el-button>
              <el-button v-if="meta.indexOf('deviceTicketSetTemplate') > -1" v-preventReClick type="primary" :disabled="!(selList && selList.length > 0)" @click="glBtn">关联模板</el-button>
            </div>
            <div class="detail" @click="manufacturerDetail(model.id)"><i class="el-icon-warning-outline" /> 厂商说明</div>
          </div>
        </el-tab-pane>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
          />
          <el-table-column align="center" label="设备ID" prop="devCode" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" label="设备名称" prop="name" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" label="设备位置" prop="devAddr" min-width="140" show-overflow-tooltip />
          <el-table-column align="center" label="设备型号" prop="devItemNo" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" label="用户名" prop="devUserName" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" label="关联模板名称" prop="devTicketTemplateName" min-width="120" show-overflow-tooltip />
          <el-table-column align="center" label="设备状态" min-width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                :active-value="'1'"
                :inactive-value="'0'"
                :disabled="meta.indexOf('deviceTicketUpdateStatus') === -1"
                @change="toConfigUpdate($event, scope.row.id, scope.row.state)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="设备在线状态" prop="connectStatus" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span
                v-if="scope.row.connectStatus === '0'"
                class="secondColor"
              >离线</span>
              <span v-else>在线</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template slot-scope="scope">
              <div class="flex-cc">
                <el-button v-if="meta.indexOf('deviceTicketUpdate') > -1" v-preventReClick type="text" @click="toEdit(scope.row)">编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
      <Paginations
        :total="totalCount"
        :page="pagination.page"
        @current-change="getList"
        @SizeChange="handleSizeChange"
      />
    </div>
    <el-dialog v-if="dialogGlmb" title="关联模板" :visible.sync="dialogGlmb" width="500px" top="20vh !important" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form
        ref="mbForm"
        class="doumee-form"
        :model="mbForm"
        :rules="rules"
        label-suffix="："
        label-width="7em"
      >
        <el-form-item label="模板名称" prop="devTicketTemplateId">
          <el-select v-model="mbForm.devTicketTemplateId" placeholder="请选择模板" clearable class="mam">
            <el-option
              v-for="item in mbList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogGlmb = false">取消</el-button>
        <el-button :loading="subLoadingb" type="primary" @click="saveBtn">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="dialogTableVisible" :title="newPrinter.id?'编辑':'新增'" :visible.sync="dialogTableVisible" width="600px" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form
        ref="newPrinter"
        class="doumee-form"
        :model="newPrinter"
        :rules="rules"
        label-suffix="："
        label-width="7em"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="newPrinter.name"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备ID" prop="devCode">
          <el-input
            v-model="newPrinter.devCode"
            placeholder="请输入设备ID"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="devUserName">
          <el-input
            v-model="newPrinter.devUserName"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="设备密码" prop="devUserPwd">
          <el-input
            v-model="newPrinter.devUserPwd"
            placeholder="请输入设备密码"
          />
          <!-- type="password" -->
        </el-form-item>
        <el-form-item label="设备型号" prop="devItemNo">
          <el-input
            v-model="newPrinter.devItemNo"
            placeholder="请输入设备型号"
          />
        </el-form-item>
        <el-form-item label="设备位置" prop="devAddr">
          <el-input
            v-model="newPrinter.devAddr"
            placeholder="请输入设备位置"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
    <Renovation v-show="tabIndex === 'two'" ref="RenovationRef" />
  </div>
</template>

<script>
import { manufacturerList, manufacturerDetail, queryMachineList, updateMachine, updateMachineStatus, addMachine, detailMachine, setDevTemplateId, devTemplateList } from '@/api'
import { parseTime } from '@/utils'
import Renovation from './renovation.vue' // 装修
import store from '@/store'
export default {
  name: 'DeviceTicket',
  components: {
    Renovation
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      tabList: [{
        label: '自助机设备',
        value: 'first'
      }, {
        label: '装修模板',
        value: 'two'
      }],
      tabIndex: 'first',
      subLoading: false,
      subLoadingb: false,
      active: '0',
      swiperOptions: {
        slidesPerView: 'auto',
        pagination: {
          el: '.swiper-pagination'
        }
      },
      pagination: {
        page: 1,
        rows: 10
      },
      dialogTableVisible: false,
      totalCount: 10,
      list: [],
      listLoading: true,
      stateList: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' }
      ],
      connectStatusList: [
        { value: '0', label: '离线' },
        { value: '1', label: '在线' }
      ],
      deviceStatus: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' }
      ],
      areaList: [],
      manufacturerList: [],
      filters: {},
      newPrinter: {},
      selList: [],
      dialogGlmb: false,
      meta: [],
      mbForm: {},
      mbList: [],
      rules: {
        name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        devTicketTemplateId: [
          { required: true, message: '请选择模板', trigger: 'change' }
        ],
        devCode: [
          { required: true, message: '请输入设备ID', trigger: 'blur' }
        ],
        devUserName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        devUserPwd: [
          { required: true, message: '请输入设备密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.listLoading = false
    this.meta = this.$route.meta.buttons || []
    this.initData()
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleSelectionChange(val) {
      this.selList = val
    },
    glBtn() {
      devTemplateList({ param: { }}).then(res => {
        if (res.errorCode === '000000') {
          this.mbList = res.recordList || []
          this.mbForm = {
            devMachineList: this.selList.map(e => e.id)
          }
          this.dialogGlmb = true
        }
      }).catch(() => {})
    },
    saveBtn() {
      this.$refs.mbForm.validate((valid) => {
        if (valid) {
          this.subLoadingb = true
          const param = { ...this.mbForm }
          setDevTemplateId({ param }).then(res => {
            // console.log(res)
            this.subLoadingb = false
            if (res.errorCode === '000000') {
              this.$message.success('关联成功')
              this.dialogGlmb = false
              this.getList()
            }
          }).catch(err => {
            this.subLoadingb = false
            console.log(err)
          })
        }
      })
    },
    handleTabClick() {
      if (this.tabIndex === 'two') {
        this.$refs.RenovationRef.getList()
      }
    },
    handleClick() {
      this.getList(1)
    },
    toConfigUpdate(e, id, status) {
      this.listLoading = true
      updateMachineStatus({ param: { id, status }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.$message.success('修改成功')
        }
        this.getList()
      }).catch(() => {
        this.listLoading = false
      })
    },
    addDevice() {
      this.newPrinter = {
        manufacturerId: this.manufacturerList[this.active].id
      }
      this.dialogTableVisible = true
    },
    toEdit(item) {
      detailMachine({ param: { id: item.id }}).then(res => {
        if (res.errorCode === '000000') {
          this.newPrinter = {
            ...res.record,
            manufacturerId: this.manufacturerList[this.active].id
          }
          this.dialogTableVisible = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    initData() {
      manufacturerList({ param: { type: 8 }}).then(res => {
        if (res.errorCode === '000000') {
          this.manufacturerList = res.recordList
          this.getList(1)
        }
      }).catch(err => {
        console.log(err)
      })
      // manufacturerDetail()
    },
    getList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      queryMachineList({ pagination, param: { venueId, manufacturerId: this.manufacturerList[this.active].id, ...filters }}).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.totalCount = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    clear() {
      this.filters = {}
      this.getList()
    },
    cancel() {
      this.dialogTableVisible = false
    },
    save() {
      this.$refs.newPrinter.validate((valid) => {
        if (valid) {
          this.subLoading = true
          const param = { ...this.newPrinter }
          if (param.id) {
            updateMachine({ param }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('编辑成功')
                this.getList()
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          } else {
            addMachine({ param }).then(res => {
              // console.log(res)
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('新增成功')
                this.getList()
                this.dialogTableVisible = false
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          }
        } else {
          // this.$alert('请先完善设备信息', '错误')
        }
      })
    },
    manufacturerDetail() {
      manufacturerDetail({ param: { manufacturerId: this.manufacturerList[this.active].id }}, sessionStorage.getItem('venueId')).then(res => {
        // console.log(res)
        if (res.errorCode === '000000') {
          const cont = res.record.manufacturer + res.record.text.replace(/\n/g, '<br/>')
          this.$alert(cont, '厂商说明', {
            dangerouslyUseHTMLString: true
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
